package com.cloud.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.core.domain.Ztree;
import com.cloud.admin.common.utils.StringUtils;
import com.cloud.admin.mapper.SysMenuMapper;
import com.cloud.admin.model.entity.SysMenu;
import com.cloud.admin.model.entity.SysRole;
import com.cloud.admin.model.entity.SysUser;
import com.cloud.admin.service.SysMenuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.*;

/**
 * 菜单权限表
 *
 * @author douhaichao code generator
 * @date 2019-07-09 10:27:05
 */
@Service
@AllArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public SysMenu selectOne(SysMenu req) {
        QueryWrapper queryWrapper = new QueryWrapper<SysMenu>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<SysMenu> selectAll(SysMenu req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<SysMenu> selectPage(Page page, SysMenu req) {
        IPage<SysMenu> list = baseMapper.selectPage(
                page,
                new QueryWrapper<SysMenu>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<SysMenu> selectPageByLike(Page page, SysMenu req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getMenuId()) {
            queryWrapper.eq("menu_id", req.getMenuId());
        }

        if (!StrUtil.isEmpty(req.getMenuName())) {
            queryWrapper.like("menu_name", req.getMenuName());
        }

        if (null != req.getParentId()) {
            queryWrapper.eq("parent_id", req.getParentId());
        }

        if (null != req.getOrderNum()) {
            queryWrapper.eq("order_num", req.getOrderNum());
        }

        if (!StrUtil.isEmpty(req.getUrl())) {
            queryWrapper.like("url", req.getUrl());
        }

        if (!StrUtil.isEmpty(req.getTarget())) {
            queryWrapper.like("target", req.getTarget());
        }

        if (!StrUtil.isEmpty(req.getMenuType())) {
            queryWrapper.like("menu_type", req.getMenuType());
        }

        if (!StrUtil.isEmpty(req.getVisible())) {
            queryWrapper.like("visible", req.getVisible());
        }

        if (!StrUtil.isEmpty(req.getPerms())) {
            queryWrapper.like("perms", req.getPerms());
        }

        if (!StrUtil.isEmpty(req.getIcon())) {
            queryWrapper.like("icon", req.getIcon());
        }

        if (!StrUtil.isEmpty(req.getCreateBy())) {
            queryWrapper.like("create_by", req.getCreateBy());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (!StrUtil.isEmpty(req.getUpdateBy())) {
            queryWrapper.like("update_by", req.getUpdateBy());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }

        if (!StrUtil.isEmpty(req.getRemark())) {
            queryWrapper.like("remark", req.getRemark());
        }
        IPage<SysMenu> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(SysMenu req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(Long userId) {
        List<String> perms = baseMapper.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<Ztree> roleMenuTreeData(SysRole role, Long userId) {
        Integer roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysMenu> menuList = selectMenuAll(userId);
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleMenuList = baseMapper.selectMenuTree(roleId);
            ztrees = initZtree(menuList, roleMenuList, true);
        } else {
            ztrees = initZtree(menuList, null, true);
        }
        return ztrees;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenu> menuList) {
        return initZtree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param menuList     菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag    是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenu> menuList, List<String> roleMenuList, boolean permsFlag) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (SysMenu menu : menuList) {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getMenuId());
            ztree.setPId(menu.getParentId());
            ztree.setName(transMenuName(menu, roleMenuList, permsFlag));
            ztree.setTitle(menu.getMenuName());
            if (isCheck) {
                ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public String transMenuName(SysMenu menu, List<String> roleMenuList, boolean permsFlag) {
        StringBuffer sb = new StringBuffer();
        sb.append(menu.getMenuName());
        if (permsFlag) {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
        }
        return sb.toString();
    }

    @Override
    public List<Ztree> menuTreeData(Long userId) {
        List<SysMenu> menuList = selectMenuAll(userId);
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }

    @Override
    public Map<String, String> selectPermsAll(Long userId) {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<SysMenu> permissions = selectMenuAll(userId);
        if (StringUtils.isNotEmpty(permissions)) {
            for (SysMenu menu : permissions) {
                section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }

    @Override
    public int selectCountMenuByParentId(Integer parentId) {
        return baseMapper.selectCount(new QueryWrapper<SysMenu>().eq("parent_id", parentId));
    }

    @Override
    public int selectCountRoleMenuByMenuId(Integer menuId) {
        return baseMapper.selectCountRoleMenuByMenuId(menuId);
    }

    @Override
    public String checkMenuNameUnique(SysMenu menu) {
        Integer menuId = StringUtils.isNull(menu.getMenuId()) ? Integer.valueOf(-1) : menu.getMenuId();
        SysMenu info = baseMapper.selectOne(new QueryWrapper<SysMenu>().eq("menu_name", menu.getMenuName()).eq("parent_id", menu.getParentId()));
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return UserConstants.MENU_NAME_UNIQUE;
    }

    @Override
    public SysMenu getMenueInfo(Integer menuId) {
        return baseMapper.selectMenueInfo(menuId);
    }

    @Override
    public List<SysMenu> selectMenusByUser(SysUser user, int platformId) {
        List<SysMenu> menus = new LinkedList<SysMenu>();
        // 管理员显示所有菜单信息
        if (user.isAdmin()) {
            menus = baseMapper.selectMenuNormalAll();
        } else {
            menus = baseMapper.selectMenusByUserId(user.getUserId());
        }
        return getChildPerms(menus, Integer.valueOf(0), platformId);
    }

    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        List<SysMenu> menuList = null;
        if (SysUser.isAdmin(userId)) {
            menuList = baseMapper.selectMenuList(menu);
        } else {
            menuList = baseMapper.selectMenuListByUserId(menu, userId);
        }
        return menuList;
    }

    @Override
    public List<SysMenu> selectMenuAll(Long userId) {
        List<SysMenu> menuList = null;
        if (SysUser.isAdmin(userId)) {
            menuList = baseMapper.selectMenuList(null);
        } else {
            menuList = baseMapper.selectMenuAllByUserId(userId);
        }
        return menuList;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list       分类表
     * @param parentId   传入的父节点ID
     * @param platformId 传入平台ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, Integer parentId, int platformId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId && t.getPlatform().intValue() == platformId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysMenu> it = childList.iterator();
                while (it.hasNext()) {
                    SysMenu n = (SysMenu) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
